/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import org.hibernate.Session;
import hibernate.connection_factory.HibernateUtil;
import hibernate.entityes.Distance;
import hibernate.entityes.DistancePK;
import java.util.List;
import org.hibernate.Hibernate;
import org.hibernate.Query;

/**
 *
 * @author eleven
 */
public class DistanceDAOImpl extends ElementDAOImpl<Distance> implements DistanceDAO {

    @Override
    public Distance getDistance(DistancePK dpk) {
        Session session = HibernateUtil.getOrInitSession();
        Distance distance = (Distance) session.load(Distance.class, dpk);
        Hibernate.initialize(distance.getDistancePK());
        session.close();
        return distance;
    }

    @Override
    public Distance getDistanceByFromCityToCity(String fromCity, String toCity) {
        Session session = HibernateUtil.getOrInitSession();
        Query q = session.getNamedQuery("Distance.findByFromCityAndToCity");
        q.setParameter("fromcity", fromCity);
        q.setParameter("tocity", toCity);
        Distance distance = null;
        if(q.list().size() > 0){
           distance = (Distance) q.list().get(0);
           Hibernate.initialize(distance);
        }        
        return distance;
    }

    @Override
    public List<Distance> getAllDistances() {
        Session session = HibernateUtil.getOrInitSession();
        Query q = session.getNamedQuery("Distance.findAll");
        List<Distance> distances = q.list();
        if (distances.size()>0) {
            distances = q.list();
            for (Distance distance : distances) {
                Hibernate.initialize(distance);
            }
        }
        else{
            distances = null;
        }
        return distances;
    }
}
